package com.lucky.ebidding.controller;

import com.google.gson.Gson;
import com.lucky.ebidding.dao.FileInfoDao;
import com.lucky.ebidding.dto.FileDTO;
import com.lucky.ebidding.model.FileInfo;
import com.lucky.ebidding.model.FileInfoExample;
import com.lucky.ebidding.model.User;
import com.lucky.ebidding.service.FileService;
import com.lucky.ebidding.service.NotificationService;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.naming.Name;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * ClassName:uploadController
 * Package:com.lucky.ebidding.controller
 * Description:
 *
 * @Date:2020/3/17 16:21
 * @Author:857251389@qq.com
 */
@Controller
public class FileController {

    @Autowired
    private FileService fileService;

    @Autowired
    private NotificationService notificationService;

    @PostMapping("/file/upload/{type}")
    @ResponseBody
    public FileDTO upload(@RequestParam("file") MultipartFile file, HttpServletRequest request,
                          @PathVariable(name = "type") Integer type,
                          HttpServletRequest request1){
        User user = (User) request.getSession().getAttribute("user");
        FileDTO fileDTO = new FileDTO();
        String Filename = file.getOriginalFilename();
        FileInfo fileInfo1 = fileService.selectByFileName(Filename);
        if(fileInfo1 == null){
            //指定存储空间的位置
            Configuration cfg = new Configuration(Zone.zone0());

            //...生成上传凭证，然后准备上传
            UploadManager uploadManager = new UploadManager(cfg);
            //配置密匙，和存储空间信息
            String accessKey = "tmorGbVAnS80R4OyqmybOQBCfZvkygYEeT2qFQJH";
            String secretKey = "QLEjhx5VEShUPgp_t-IpHWmTX0SQaiUgTt4kLu1J";
            String bucket = "lxxfileupload";
            //默认不指定key的情况下，以文件内容的hash值作为文件名
            String key = file.getOriginalFilename();

            String imgURl = "";


            try {
                InputStream byteInputStream = file.getInputStream();
                Auth auth = Auth.create(accessKey, secretKey);
                String upToken = auth.uploadToken(bucket);
                try {
                    Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
                    //解析上传成功的结果
                    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                    imgURl = putRet.hash;
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setFileName(file.getOriginalFilename());
                    fileInfo.setFileUrl("http://qaz9sj3rt.bkt.clouddn.com/"+key);
                    fileInfo.setType(type);
                    fileInfo.setUserId(user.getId());
                    int i = fileService.insertFile(fileInfo);

                    if(i!=0){
                        fileDTO.setCode(200);
                        fileDTO.setUrl("http://qaz9sj3rt.bkt.clouddn.com/"+imgURl);
                        fileDTO.setMessage("上传成功");
                        fileDTO.setFileId(fileInfo.getId());
                        return fileDTO;
                    }
                } catch (QiniuException ex) {
                    Response r = ex.response;
                    System.err.println(r.toString());
                    try {
                        System.err.println(r.bodyString());
                    } catch (QiniuException ex2) {
                        //ignore
                    }
                }
            } catch (UnsupportedEncodingException ex) {
                //ignore
            } catch (IOException e) {
                e.printStackTrace();
            }

            fileDTO.setCode(0);
            fileDTO.setUrl("");
            fileDTO.setMessage("上传失败");

            return fileDTO;
        }
        fileDTO.setCode(200);
        fileDTO.setUrl(fileInfo1.getFileUrl());
        fileDTO.setFileId(fileInfo1.getId());
        fileDTO.setMessage("上传成功");
        return fileDTO;
    }

    @GetMapping("/file/zbFIleDownload/{zbId}")
    public String zbFileDownload(@PathVariable(name = "zbId") Integer zbId, Model model){

        FileInfo fileInfo = fileService.selectByZbId(zbId);

        model.addAttribute("FileInfo",fileInfo);

        return "zb/zb_fileDownload";
    }

}
